package com.ylx.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//检查用户是否登录的过滤器，过滤器是过滤所有资源，包括静态资源，css，js,jsp，开发时要注意指定哪些不要过滤
@WebFilter("")
public class CheckLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //注意登录注册和一些不需要过滤的需要放行
        HttpServletRequest request =(HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) resp;
        //获得用户提交的uri
        String uri = request.getRequestURI();
        //contains:表示字符串中是否包含某个值
        if (uri.contains("login.jsp")
            ||uri.contains("404.jsp")
            ||uri.contains("LoginServlet")
            ||uri.contains("CheckCodeUtile")
            ||uri.endsWith(".js")
            ||uri.endsWith(".css")
            ||uri.contains("layui")
            ||uri.contains("logincss")
            ||uri.contains("imgs")
            ||uri.contains("register.jsp")
            ||uri.contains("register.do")){
            //放行
            chain.doFilter(req, resp);
        }else{
            //要判断用户是否登录
            //获得session中用户对象，如果这个对象是Null则表明用户没有登录需要直接跳转到登录界面
            HttpSession session = request.getSession();
            Object us = session.getAttribute("us");
            if (us==null){
              response.sendRedirect("/login.jsp");
            }else {
                //放行
                chain.doFilter(req, resp);
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
